/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.graph;

/**
 *
 * @author joep
 */
import com.bayu.common.lib.CommonUtil;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import com.bayu.controller.MainController;
import com.bayu.services.dao.AvgStopTimeDao;
import com.bayu.services.dao.GraphCsHollowDao;
import com.bayu.services.entity.AvgStopTime;
import com.bayu.services.entity.GraphCsHollow;
import java.awt.Color;
import java.io.OutputStream;
import java.util.List;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class GraphCsHollowGraph {

    GraphCsHollowDao graphCsHollowDao;
    AvgStopTimeDao avgStopTimeDao;

    @Autowired
    private void setGraphCsHollowDao(GraphCsHollowDao graphCsHollowDao){
      this.graphCsHollowDao = graphCsHollowDao;
    }

    @Autowired
    private void setavgStopTimeDao(AvgStopTimeDao avgStopTimeDao) {
        this.avgStopTimeDao = avgStopTimeDao;
    }

    @RequestMapping("/graph-cs-hollow-graph.png")
    private void graphCsHollowGraph (OutputStream stream) throws Exception{

        List maxValue= graphCsHollowDao.custom("select max(actualcshlw)+max(batasmax) from GraphCsHollow where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
        //List maxValue2 = graphCsHollowDao.custom("select max(frekwensi) from GraphPms where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
        //String strMax2 = maxValue2.get(0).toString();
        String strMax = maxValue.get(0).toString();
        //System.out.println(strMax2+"-"+strMax);

        double max1 = Double.valueOf(strMax).doubleValue()+10;
        //double max2 = Double.valueOf(strMax2).doubleValue()+1;



        double min = 0.0;
        //double max = maxtemp+2;
        JFreeChart chart = getCsHollowGraph(min, max1);
        ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
    }

    private JFreeChart getCsHollowGraph(Double min,double max1){
       DefaultCategoryDataset dataset1 = graphCsHollowDataset1();

       String tgl1="";
       String tgl2="";
       String title = "STOP TIME CAM SHAFT HOLLOW";

      if(!MainController.startDate.equals("")){
          tgl1 = CommonUtil.formatStringDate(MainController.startDate);
          tgl2 = CommonUtil.formatStringDate(MainController.endDate);
          title = title+"\r\n"+ tgl1+"-"+tgl2;
      }

      final JFreeChart chart = ChartFactory.createBarChart(
            title,        // chart title
           "MONTH",               // domain axis label
           "Stop Time(menit)",                  // range axis label
            dataset1,                 // data
            PlotOrientation.VERTICAL,
            true,                     // include legend
            true,                     // tooltips?
            false                     // URL generator?  Not required...
        );
        chart.setBackgroundPaint(new Color(255, 255, 255));
        CategoryPlot plot = chart.getCategoryPlot();

        plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

        CategoryItemRenderer renderer1 = plot.getRenderer();
        renderer1.setSeriesPaint(0, new Color(153,51,102));
        renderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER));
        renderer1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
        renderer1.setBaseItemLabelsVisible(true);

        DefaultCategoryDataset dataset2 = graphCsHollowDataset2();


        plot.setDataset(1,dataset2);
        CategoryItemRenderer renderer2 = new LineAndShapeRenderer();

        renderer2.setSeriesPaint(0, Color.orange);
        renderer2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer2.setBaseItemLabelsVisible(true);
        plot.setRenderer(1, renderer2);

        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
        //Set Minimum dan Maximum Value Axis
        rangeAxis.setRange(min, max1);

        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

       return chart;

    }

    public DefaultCategoryDataset graphCsHollowDataset1(){
        String rowValue="Actual(menit)C/S HLW";
        DefaultCategoryDataset data1 = new DefaultCategoryDataset();
        String[] temp;
        String cat;
        List data = this.graphCsHollowDao.getAllByDate(MainController.startDate, MainController.endDate);
        List rata = this.avgStopTimeDao.custom("from AvgStopTime where jenis = 'actual CS HLW'");

        /*
         * Ambil data tahun 2008,2009,2010
         */
        for (int j=0;j<rata.size();j++) {
            AvgStopTime st = (AvgStopTime)rata.get(j);
            data1.addValue(st.getAverage(), rowValue, "AVG" + Integer.toString(st.getTahun()));
            System.out.println("ActualCsHlwAvg "+st.getAverage());
        }
        /*****************************************************************************************/

        /*
         * Ambil rata2 tahun sekarang
         
        List curAvg = graphCsHollowDao.custom("select avg(actualcshlw) from GraphCsHollow"+
                         " where YEAR(date) = '"+
                         Integer.toString(CommonUtil.getCurrentYear()) +"'");
        String strcurAvg = curAvg.get(0).toString();
        data1.addValue(Double.parseDouble(strcurAvg),
                rowValue,
                "AVG" + Integer.toString(CommonUtil.getCurrentYear()));

        saveAvg(CommonUtil.getCurrentYear(), Double.parseDouble(strcurAvg), "actual CS HLW");

        System.out.println("Rata2 actualCsHlw th "+
                Integer.toString(CommonUtil.getCurrentYear())+" = "+strcurAvg);
        /*****************************************************************************************/

        /*
         * Data bulanan
         */
        for(int i=0;i<data.size();i++){
          GraphCsHollow dt = (GraphCsHollow)data.get(i);
          temp = dt.getDate().toString().split("-");
          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));

          data1.addValue(dt.getActualcshlw(), rowValue, cat);

          System.out.println("ActualCsHlw "+dt.getActualcshlw()+"-"+cat);
        }

        return data1;
    }

    public DefaultCategoryDataset graphCsHollowDataset2(){
        String rowValue="BatasMax(menit)";
        DefaultCategoryDataset data1 = new DefaultCategoryDataset();
        String[] temp;
        String cat;
        List data = this.graphCsHollowDao.getAllByDate(MainController.startDate, MainController.endDate);
        List rata = this.avgStopTimeDao.custom("from AvgStopTime where jenis = 'batas max CS HLW'");

        /*
         * Ambil data tahun 2008,2009,2010
         */
        for (int j=0;j<rata.size();j++) {
            AvgStopTime st = (AvgStopTime)rata.get(j);
            data1.addValue(st.getAverage(), rowValue, "AVG" + Integer.toString(st.getTahun()));
            System.out.println("BatasMaxAvg "+st.getAverage());
        }
        /*****************************************************************************************/

        /*
         * Ambil rata2 tahun sekarang
         
        List curAvg = graphCsHollowDao.custom("select avg(batasmax) from GraphCsHollow"+
                         " where YEAR(date) = '"+
                         Integer.toString(CommonUtil.getCurrentYear()) +"'");
        String strcurAvg = curAvg.get(0).toString();
        data1.addValue(Double.parseDouble(strcurAvg),
                rowValue,
                "AVG" + Integer.toString(CommonUtil.getCurrentYear()));

        saveAvg(CommonUtil.getCurrentYear(), Double.parseDouble(strcurAvg), "batas max CS HLW");

        System.out.println("Rata2 batasMAX th "+
                Integer.toString(CommonUtil.getCurrentYear())+" = "+strcurAvg);
        /*****************************************************************************************/

        /*
         * Data bulanan
         */
        for(int i=0;i<data.size();i++){
          GraphCsHollow dt = (GraphCsHollow)data.get(i);
          temp = dt.getDate().toString().split("-");
          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));

          data1.addValue(dt.getBatasmax(), rowValue, cat);

          System.out.println("BatasMax "+dt.getBatasmax()+"-"+cat);
        }
/*
        List curAvg2 = graphCsHollowDao.custom("select avg(frekwensi) from GraphCsHollow"+
                         " where YEAR(date) = '"+
                         Integer.toString(CommonUtil.getCurrentYear()) +"'");
        strcurAvg = curAvg2.get(0).toString();
        saveAvg(CommonUtil.getCurrentYear(),Double.parseDouble(strcurAvg),"frekwensi CS HLW");
*/
        return data1;
    }



    /*
     * FUngsi cek dan update data tahun sekarang
     */
    private void saveAvg(int tahun, double average, String jenis){
        List svAvg = avgStopTimeDao.custom("from AvgStopTime where "+
                "tahun= "+Integer.toString(tahun)+
                " AND jenis='"+jenis+"'");
        AvgStopTime inpAvg;
        if (svAvg.size() > 0) {
            inpAvg = (AvgStopTime)svAvg.get(0);
            this.avgStopTimeDao.delete(inpAvg);
        }
        inpAvg = new AvgStopTime();
        inpAvg.setTahun(tahun);
        inpAvg.setJenis(jenis);
        inpAvg.setAverage(average);

        this.avgStopTimeDao.save(inpAvg);
    }

}
